<template>
  <a-modal
    :title="title"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" v-if="!editFlag">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="表名">
          <a-input placeholder="请输入表名" v-decorator="[ 'tableName', validatorRules.tableName]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="框架类型">
          <a-select placeholder="请选择框架类型"
                    :options="systemTypeList"
                    v-decorator="['systemId', validatorRules.systemId]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="数据源">
          <a-select placeholder="请选择数据源"
                    :options="dataSourceList"
                    v-decorator="['dataSourceId', validatorRules.dataSourceId]" />
        </a-form-item>
      </a-form>
      <a-form :form="form" v-if="editFlag">
        <a-row :gutter="24">
          <a-col :md="12" :sm="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="表名">
              <a-input placeholder="请输入表名称" v-decorator="[ 'tableName', {}]" :disabled="true"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="实体名称">
              <a-input placeholder="请输入实体名称" v-decorator="[ 'entityName', {}]" :disabled="true"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="主键名称">
              <a-input placeholder="请输入主键名称" v-decorator="[ 'primaryName', {}]" :disabled="true"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="主键属性名称">
              <a-input placeholder="请输入主键属性名称" v-decorator="[ 'primaryField', {}]" :disabled="true"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="主键策略">
              <j-dict-select-tag placeholder="请选择主键策略" dict-code="primaryKeyGenerate"
                                 v-decorator="[ 'primaryKeyStrategy', validatorRules.primaryKeyStrategy]"
                                 :trigger-change="true" @change="primaryChange"></j-dict-select-tag>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="8" v-if="sequence">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="序列名称">
              <a-input placeholder="请输入序列名称" v-decorator="[ 'sequence', validatorRules.sequence]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="是否POI">
              <a-radio-group placeholder="是否POI" v-decorator="[ 'poiEnable', {}]">
                <a-radio value="1">是</a-radio>
                <a-radio value="0">否</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="是否生成操作日志">
              <a-radio-group placeholder="是否生成操作日志" v-decorator="[ 'operateLogFlag', {}]">
                <a-radio value="1">是</a-radio>
                <a-radio value="0">否</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="业务包名称">
              <a-input placeholder="请输入业务包名称" v-decorator="[ 'bussiPath', validatorRules.bussiPath]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="swagger接口">
              <a-radio-group placeholder="swagger接口" v-decorator="[ 'swaggerGenerateFlag', {}]">
                <a-radio value="1">是</a-radio>
                <a-radio value="0">否</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="默认排序字段">
              <a-select placeholder="请选择默认排序字段" v-decorator="[ 'defaultOrder', {}]" :options="orderList"
                        :trigger-change="true">
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="排序类型">
              <a-select placeholder="请选择默认排序字段" v-decorator="[ 'orderType', {}]"
                        :trigger-change="true">
                <a-select-option value="">请选择</a-select-option>
                <a-select-option value="desc">降序</a-select-option>
                <a-select-option value="asc">升序</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="表说明">
              <a-input placeholder="请输入表说明" v-decorator="[ 'tableDescripe', validatorRules.tableDescripe]"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import pick from 'lodash.pick'
  import {getAction, downFile} from "../../../api/manage";

  export default {
    name: 'FormDesignModal',
    props:{
      systemTypeList:{
        type:Array,
        required:true,
        default:()=>{},
      },
      dataSourceList:{
        type:Array,
        required:true,
        default:()=>{},
      }
    },
    data() {
      return {
        value: 1,
        title: '操作',
        visible: false,
        editFlag: false,
        sequence: false,
        defaultOrder: '',
        model: {},
        labelCol: {
          xs: {span: 24},
          sm: {span: 5}
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16}
        },
        orderList: [],
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
          primaryKeyStrategy: {rules: [{required: true, message: '请选择主键生成策略!'}]},
          bussiPath: {rules: [{required: true, message: '请输入业务包名称!'}]},
          tableDescripe: {rules: [{required: true, message: '请输入表描述!'}]},
          sequence: {rules: [{required: true, message: '请输入序列名称!'}]},
        },
        url: {
          addTable: 'generator/table/addTable',
          editTable: 'generator/table/editTable',
          orderList: 'generator/table/column/getColumnField'
        }
      }
    },
    created() {
    },
    methods: {
      add() {
        this.editFlag = false;
        this.form.resetFields();
        this.visible = true
      },
      primaryChange(value) {
        if (value == '3') {
          this.sequence = true;
        } else {
          this.sequence = false;
        }
      },
      async orderFieldList(tableName) {
        await getAction(this.url.orderList, {tableName: tableName}).then(res => {
          if (res.success) {
            this.orderList = res.result;
            this.orderList.forEach(item => {
              if (item.value == 'createTime') {
                this.defaultOrder = item.value;
              }
            });
          }
        });
      },
      async edit(record) {
        this.visible = true
        this.editFlag = true;
        this.defaultOrder = '';
        await this.orderFieldList(record.tableName);
        this.form.resetFields()
        this.model = Object.assign({}, record)
        if (!this.model.poiEnable) {
          this.model.poiEnable = "1";
        }
        if (!this.model.operateLogFlag) {
          this.model.operateLogFlag = "1";
        }
        if (!this.model.sequence) {
          this.model.sequence = false;
        } else {
          if (this.model.primaryKeyStrategy == '3') {
            this.sequence = true;
          }
        }
        if (!this.model.swaggerGenerateFlag) {
          this.model.swaggerGenerateFlag = "1";
        }
        if (this.defaultOrder) {
          this.model.defaultOrder = this.defaultOrder;
        }
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'tableName', 'entityName', 'primaryName', 'primaryField', 'primaryKeyStrategy', 'poiEnable', 'bussiPath', 'operateLogFlag', 'swaggerGenerateFlag', 'defaultOrder', 'tableDescripe','orderType','systemId','dataSourceId'));
          if (this.model.primaryKeyStrategy == '3') {
            this.form.setFieldsValue("sequence", this.model.sequence);
          }
        })
      },
      // 确定
      handleOk() {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let formData = Object.assign(this.model, values);
            if (this.editFlag) {
              debugger;
              downFile(this.url.editTable,formData).then((data)=>{
                if (!data) {
                  that.$message({message:"文件下载失败",type:'error'});
                  return
                }
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                  window.navigator.msSaveBlob(new Blob([data],{type: 'application/zip'}), "生成代码.ZIP")
                }else{
                  let url = window.URL.createObjectURL(new Blob([data],{type: 'application/zip'}))
                  let link = document.createElement('a')
                  link.style.display = 'none'
                  link.href = url
                  link.setAttribute('download', "生成代码.ZIP")
                  document.body.appendChild(link)
                  link.click()
                  document.body.removeChild(link); //下载完成移除元素
                  window.URL.revokeObjectURL(url); //释放掉blob对象
                }
                that.$emit('ok')
                that.close();
              }).finally(() => {
                that.confirmLoading = false
              });
            } else {
              getAction(this.url.addTable, {"tableName": values.tableName,"systemId":values.systemId,"dataSourceId":values.dataSourceId}).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                  that.close();
                } else {
                  that.$message.warning(res.message)
                }
              }).finally(() => {
                that.confirmLoading = false
              })
            }
          }
        })
      },
      // 关闭
      handleCancel() {
        this.close()
      },
      close() {
        this.$emit('close')
        this.visible = false
      }
    }
  }
</script>